package com.sxf.rental.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxf.rental.entity.AutoInfo;
import com.sxf.rental.entity.Order;
import com.sxf.rental.mapper.AutoInfoMapper;
import com.sxf.rental.mapper.OrderMapper;
import com.sxf.rental.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sxf
 * @since 2025-03-08
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Resource
    private AutoInfoMapper autoInfoMapper;
    @Override
    public boolean insert(Order order) {
        Integer autoId = order.getAutoId();
        AutoInfo autoInfo = autoInfoMapper.selectById(autoId);
        autoInfo.setStatus("1");
        autoInfoMapper.updateById(autoInfo);
        String number = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now());
        order.setOrderNum(number);
        order.setRentalTime(LocalDateTime.now());
        return baseMapper.insert(order)>0;
    }

    @Override
    public Page<Order> searchUnfinished(Page<Order> page, Order order) {
        return baseMapper.searchUnfinished(page,order);
    }

    @Override
    public boolean returnAuto(Order order, Integer maintainMileage) {
        //修改车辆的状态
       try{
           AutoInfo autoInfo = autoInfoMapper.selectById(order.getAutoId());
        autoInfo.setStatus("0");
        //增加车辆行驶历程
        autoInfo.setMileage(order.getReturnMileage());
        //修改应保状态
        autoInfo.setExpectedNum(autoInfo.getMileage()/maintainMileage);
        autoInfoMapper.updateById(autoInfo);
        //update更新订单
        baseMapper.updateById(order);
        return true;
       }catch (Exception e){
            throw new RuntimeException("还车失败");
       }
    }

    @Override
    public Page<Order> search(Page<Order> page, Order order) {
        return baseMapper.search(page,order);
    }

    @Override
    public long countViolation(Integer autoId) {
        return baseMapper.countViaAutoId(autoId);
    }
}
